Answer:

Linear Search

Searching for an Element

Linear search starts at the first element and examines elements one by one until the target element is found. You could write linear search for an ArrayList but there is a method that does this for you:

int indexOf(Object element)    //  Search for the first occurrence of 
                               //  element, testing for equality 
                               //  using the equals(Object) method of element. 

The method returns the index of the first occurrence of element or -1 if element is not found.

QUESTION 16:

Examine the following program. What will it print?


import java.util.* ;
class SearchEg
{
  public static void main ( String[] args)
  {
    ArrayList<String> names = new ArrayList<String>();

    names.add( "Amy" );     names.add( "Bob" );
    names.add( "Chris" );   names.add( "Deb" );
    names.add( "Elaine" );  names.add( "Joe" );

    System.out.println( names.indexOf( "Elaine" ) ); 
    System.out.println( names.indexOf( "Zoe" ) ); 
  }
}